import { useEffect } from 'react';
import { getQueryString } from '@/utils/tools';
import { loginos, setDingUserInfo } from '@/request/dingCodeToken';
import localDb from '@/utils/localDB';
import getConfig from 'next/config';

export default function DingUserInfo() {
  // 数据入库
  const addData = async (params, redirect: string) => {
    const {
      publicRuntimeConfig: { APP_LOGIN_CHECK },
    }: { publicRuntimeConfig: EnvParamsType } = getConfig();
    try {
      const res: any = await setDingUserInfo(params);
      console.log(res);
      localDb.set('userInfo', res);
      localDb.set('jwtToken', res.token);
      window.location.replace(redirect);
    } catch (e) {
      window.location.href = `${APP_LOGIN_CHECK}/#/loginos?redirect=${encodeURIComponent(redirect)}`;
      console.log(e);
    }
  };

  // 获取用户信息
  const getUserInfo = async (code, redirect: string) => {
    const {
      publicRuntimeConfig: { APP_LOGIN_CHECK },
    }: { publicRuntimeConfig: EnvParamsType } = getConfig();
    try {
      const res = await loginos(code);
      addData(res, redirect);
    } catch (e) {
      console.log(e);
      window.location.href = `${APP_LOGIN_CHECK}/#/loginos?redirect=${encodeURIComponent(redirect)}`;
    }
  };

  useEffect(() => {
    const code: string = getQueryString('dingCode') || '';
    const redirect: string = getQueryString('redirect') || '';
    getUserInfo(code, redirect);
  }, []);
  return <div></div>;
}
